package com.newtouch.bxzs.common.base.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 调用外部接口utils
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/3/4 13:20</td>
 * <td>yuanjie</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author yuanjie
 * @version 1.0.0
 * @since 1.0.0
 */
public class SendHttpRequestUtils<T> {

    private RestTemplate restTemplate = new RestTemplate();

    private HttpHeaders headers = new HttpHeaders();

    public SendHttpRequestUtils(){
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.setContentType(MediaType.APPLICATION_JSON);
        List<MediaType> mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        headers.setAccept(mediaTypeList);
    }

    /**
     * 发送post请求返回Object
     * @param object 入参
     * @param url 接口路径
     */
    public Object sendHttpRequest(T object,String url){
        HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(object),headers);
        return restTemplate.postForEntity(url, entity, Object.class).getBody();
    }

    /**
     * 发送post请求返回JSONObject
     * @param object 入参
     * @param url 接口路径
     */
    public JSONObject sendHttpRequestToJson(T object,String url){
        HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(object),headers);
        return restTemplate.postForEntity(url, entity, JSONObject.class).getBody();
    }

    /**
     * 发送post请求返回JSONArray
     * @param object 入参
     * @param url 接口路径
     */
    public JSONArray sendHttpRequestToArray(T object, String url){
        HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(object),headers);
        return restTemplate.postForEntity(url, entity, JSONArray.class).getBody();
    }

}
